package com.u.finance.user.service.impl;

import com.u.finance.user.entity.Loans;
import com.u.finance.user.entity.TradeHistory;
import com.u.finance.user.entity.User;
import com.u.finance.user.entity.UserScore;
import com.u.finance.user.mapper.UserMapper;
import com.u.finance.user.service.ILoansService;
import com.u.finance.user.service.ITradeHistoryService;
import com.u.finance.user.service.IUserScoreService;
import com.u.finance.user.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Alex Wu
 * @since 2025-03-28
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private IUserScoreService userScoreService;

    @Autowired
    private ILoansService loansService;

    @Autowired
    private ITradeHistoryService tradeHistoryService;

    @Autowired
    private KieSession kieSession;

    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0 0 1 * * ?")
    public void UserRating() {
        // 给用户评级
        System.out.println("UserRating");

        List<User> users = this.list();

        List<Loans> loans = loansService.list();
        List<TradeHistory> tradeHistories = tradeHistoryService.list();
        for (User user : users) {
            UserScore userScore = new UserScore();
            kieSession.insert(user);
            kieSession.insert(userScore);
            loans.forEach(kieSession::insert);
            tradeHistories.forEach(kieSession::insert);
            kieSession.fireAllRules();
            updateUserScore(userScore);
            System.out.println("更新到 redis 缓存");
            redisTemplate.opsForValue().set("user_score_" + user.getId(), userScore.getRole());
        }
    }

    private void updateUserScore(UserScore userScore) {
        UserScore curUserScore = userScoreService.getById(userScore.getUserId());
        if (curUserScore == null) {
            userScoreService.save(curUserScore);
        } else {
            userScoreService.updateById(curUserScore);
        }
    }
}
